package com.dukk.gis.tools;

import org.locationtech.jts.geom.*;
import org.locationtech.proj4j.*;

/**
 * 坐标参考系转换
 */
public class CoordinateTransformTool {

    static GeometryFactory geometryFactory = GeoTool.getGeoFactory();

    public static Coordinate transform(Coordinate coordinate, String srcEpsg, String targetEpsg){

        CRSFactory crsFactory = new CRSFactory();
        CoordinateReferenceSystem srcCRS = crsFactory.createFromName(srcEpsg);
        CoordinateReferenceSystem targetCRS = crsFactory.createFromName(targetEpsg);

        CoordinateTransformFactory ctFactory = new CoordinateTransformFactory();
        CoordinateTransform crsTrans = ctFactory.createTransform(srcCRS, targetCRS);

        // `result` is an output parameter to `transform()`
        ProjCoordinate result = new ProjCoordinate();
        crsTrans.transform(new ProjCoordinate(coordinate.x, coordinate.y,coordinate.z), result);

        return new Coordinate(result.x, result.y, result.z);

    }

    public static Geometry transform(LineString lineString, String srcEpsg, String targetEpsg){
        Coordinate coordinates[] = lineString.getCoordinates();
        CoordinateList coordinateList = new CoordinateList();
        for(Coordinate coordinate : coordinates){
            coordinateList.add(transform(coordinate, srcEpsg, targetEpsg));
        }

        return geometryFactory.createLineString(coordinateList.toCoordinateArray());

    }

    public static Geometry transform(Polygon polygon, String srcEpsg, String targetEpsg){
        Coordinate coordinates[] = polygon.getCoordinates();
        CoordinateList coordinateList = new CoordinateList();
        for(Coordinate coordinate : coordinates){
            coordinateList.add(transform(coordinate, srcEpsg, targetEpsg));
        }

        return geometryFactory.createPolygon(coordinateList.toCoordinateArray());

    }


}
